import {useState, useEffect} from 'react';

const useCascadeNavigator = function(origData, editable) {

  const [history, setHistory] = useState([]);
  const [sublist, setSublist] = useState(origData);

  useEffect(() => {
    setHistory([]);
    setSublist(origData);
  }, [origData]);

  const enter = (record) => {
    const {succ} = record;
    console.log('ENTER', record);

    if ((editable && record.succ) || (record.succ?.length > 0)) {
      setHistory([...history, record]);
      setSublist(succ);
    }
  }

  const leave = (record) => {

    console.log('LEAVE', record);

    const currIndex = history.indexOf(record);
    const newHist = history.slice(0, currIndex);
    setHistory(newHist);

    if (newHist.length === 0){
      setSublist(origData);
    } else {
      const lastElem = newHist.slice(-1)[0];
      setSublist(lastElem.succ);
    }
  }

  return {
    history,
    sublist,
    enter,
    leave,
  }
}

export default useCascadeNavigator;